package de.infotheo;

import java.math.BigInteger;

/**
 * The class LogG contains a method to calculate the discrete log of an input
 * value
 * 
 * @author Eugen
 * 
 */
public class LogG {

	/**
	 * The method calcLogG calculates the discrete log of g by the enumeration method (brute force)
	 * 
	 * @param g base
	 * @param h result of g^x mod p
	 * @param p modulus
	 * 
	 * @return result of the discrete log
	 */
	public int calcLogG(int g, int h, int p) {

		// initiation of parameters
		BigInteger bigX = new BigInteger("0");
		BigInteger bigG = new BigInteger(Integer.toString(g));
		BigInteger bigH = new BigInteger(Integer.toString(h));
		BigInteger bigMod = new BigInteger(Integer.toString(p));
		int res = 0;

		// iteration from 0 to h while calculating g^x mod p and increment of x after each iteration
		do {

			res = Integer.parseInt(bigG.modPow(bigX, bigMod).toString());

			bigX = bigX.add(new BigInteger("1"));

		} while (res != Integer.parseInt(bigH.toString()));

		System.out.println("log_" + g + " " + h + " mod " + p + " = "
				+ Integer.parseInt(bigX.add(new BigInteger("-1")).toString()));
		return Integer.parseInt(bigX.add(new BigInteger("-1")).toString());
	}
}
